package com.listen.service.impl;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import com.listen.common.DateFormatUtil;
import com.listen.common.IPProxyNew;
import com.listen.common.StringUtil;
import com.listen.dao.AddressMapper;
import com.listen.dao.ListenLogMapper;
import com.listen.dao.StartFlagMapper;
import com.listen.dao.StudyMapper;
import com.listen.dao.UserMapper;
import com.listen.model.Address;
import com.listen.model.AddressExample;
import com.listen.model.ListenLog;
import com.listen.model.Study;
import com.listen.model.StudyCriteria;
import com.listen.model.User;
import com.listen.service.StudyService;
import com.listen.service.DB.Badayuan;
@Service
public class StudyServiceImpl implements StudyService {

	private static final Logger log = LoggerFactory.getLogger(StudyServiceImpl.class);
	
	@Resource
	private UserMapper userMapper;
	
	@Resource
	private StartFlagMapper startFlagMapper;
	
	@Resource
	private AddressMapper addressMapper;
	
	@Resource
	private ListenLogMapper listenLogMapper;
	
	@Resource
	private StudyMapper studyMapper;
	
	
	@Override
	public List<Study> selectStudyList() {
		List<Study> studyList = studyMapper.selectByExample(new StudyCriteria());
		
		List<Address> addressList = addressMapper.selectByExample(new AddressExample());
		for(Study s :studyList){
			String uzy = StringUtil.getZyByName(s.getZyName());
			if(uzy==null || "".equals(uzy.trim()))
				continue;
			for(Address a :addressList){
				String azy = a.getZy();
				if(uzy.equalsIgnoreCase(azy)){
					s.setPrefixUrl(a.getUrl());
				}
			}
		}
		if(studyList != null && studyList.size() > 0) {
			return studyList;
		}else {
			return null;
		}
	}
	
	
	//听课
	@Override
	public int updateBadayuan(Study sty,int i){
		Map<String,Object> resultMap = null;
		int result = 0;
		String oldIp = sty.getIp();
		Badayuan badayuan = new Badayuan();
		try {
			Date now = new Date();
			Date createTime = sty.getCreateTime();
			Date createTimeAfter40 = DateFormatUtil.getDateAnyMinuteAfter(createTime,40);
			if(DateFormatUtil.compareDate(now, createTimeAfter40)) {
				//先用表中的IP执行
				if(StringUtils.isNoneBlank(oldIp)) {
					resultMap = badayuan.updateStudyVideo(sty, oldIp);
					resultMap = resultMap == null ? new HashMap<String,Object>() :resultMap;
					String msg = (String) resultMap.get("msg");
					String successFlag = (String) resultMap.get("successFlag");
					log.info((i+1)+"-"+oldIp+"第0次-->"+msg);
					if("1".equals(successFlag)) {
						//2成功后删除cookie记录
						studyMapper.deleteByPrimaryKey(sty.getId());
						//3更新听课信息并保存日志
						User user = userMapper.selectByPrimaryKey(sty.getUid());
						user.setIp(sty.getIp());
						saveInfo(resultMap,user);
						result = 1;
					}else {
						result = proxyUpdate(sty,i);
					}
				}else {
					result = proxyUpdate(sty,i);
				}
			}else {
				log.info(sty.getZyName()+"-"+sty.getCode()+"-未满40分钟，开听时间为："+DateFormatUtil.getDateStr(createTimeAfter40));
				result = -1;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return result;
	}
	
	public int proxyUpdate(Study sty,int i) throws Exception {
		int result = 0;
		Badayuan badayuan = new Badayuan();
		Map<String,Object> resultMap = null;
		IPProxyNew proxy = new IPProxyNew(this.getProxyURL());
		//1.执行视频更新操作
		int k = 1;
		do{
			Thread.sleep(2000);
			String ip = proxy.getOneIpAndPort();
			resultMap = badayuan.updateStudyVideo(sty, ip);
			resultMap = resultMap == null ? new HashMap<String,Object>() :resultMap;
			String msg = (String) resultMap.get("msg");
			String successFlag = (String) resultMap.get("successFlag");
			log.info((i+1)+"-"+ip+"-第"+k+"次,-->"+msg);
			if("1".equals(successFlag)) {
				//2成功后删除cookie记录
				studyMapper.deleteByPrimaryKey(sty.getId());
				//3更新听课信息并保存日志
				User user = userMapper.selectByPrimaryKey(sty.getUid());
				user.setIp(sty.getIp());
				saveInfo(resultMap,user);
				result = 1;
				break;
			}
			k++;
			if(result != 1) {
				if(k <= 2) {
					ip = proxy.getOneIpAndPort();
				}if(k > 2) {
					//尝试3次不行，则用本机IP
					ip = null;
				}if(k > 3) {
					//尝试5次不行，则放弃
					studyMapper.deleteByPrimaryKey(sty.getId());
					break;
				}
				
			}
		}while(result == 1);
		return result;
	}
	
	private void saveInfo(Map<String,Object> resultMap,User user) {
		String msg = (String) (resultMap.get("msg")==null?"":resultMap.get("msg"));
		
		//1保存听课日志
		ListenLog log = new ListenLog();
		log.setMsg(msg);
		log.setCode(user.getCode());
		log.setUid(user.getId());
		log.setUpdateTm(new Date());
		log.setClassNo(user.getNowNum());
		listenLogMapper.insertSelective(log);
		
		//2更新听课记录
		String dayNum = (String) resultMap.get("dayNum");
		String addNum = (String) resultMap.get("addNum");
		String status = (String) resultMap.get("status");
		int todayNum = user.getTodayNum();//当天听课节数
		int nowNum = user.getNowNum();//当前总听课节数
		todayNum = todayNum + Integer.parseInt(dayNum);
		nowNum = nowNum+Integer.parseInt(addNum);
		//更新课程状态
		user.setNowNum(nowNum);
		user.setTodayNum(todayNum);
		user.setStatus(Integer.parseInt(status));
		user.setUpdateTm(new Date());
		userMapper.updateByPrimaryKeySelective(user);
	}
	
	@Override
	public String getProxyURL() {
		AddressExample addressExample = new AddressExample();
		addressExample.createCriteria().andZyEqualTo("IP");
		List<Address> address =  addressMapper.selectByExample(addressExample);
		return address == null ? null : address.get(0).getUrl();
	}

}
